package com.print.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.print.domain.Item;
import com.print.domain.User;
import com.print.domain.UserItem;

public class UserDAOImpl implements UserDAO {

	private HibernateTemplate hibernateTemplate;
	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}
	
	@Override
	public void saveUser(User user) {
		this.hibernateTemplate.saveOrUpdate(user);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> listUser() {
		return hibernateTemplate.find("from User");
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public User getUser(String username) {
		List<User> list = hibernateTemplate.find("from User where user_username = ?", username);
		if (!list.isEmpty())
			return list.get(0);
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public User getUser(String username, String password) {
		List<User> list = hibernateTemplate.find("from User where user_username = ? and user_password = ?", username, password);
		if (!list.isEmpty())
			return list.get(0);
		return null;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Item> getStampe(User user) {
		List<Item> items = hibernateTemplate.find("select i.name, i.prezzo from stampa s, item i where s.user_username = ? and s.item_id = i.item_id ", user.getUsername());
		return items;
	}
	
	@Override
	public void updateUser(User user) {
		this.hibernateTemplate.update(user);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<User> listNotAdmin() {
		return (List<User>) hibernateTemplate.find("from User "
				+ " where admin = false");
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean deleteUser(String username) {
		try {
			User user = getUser(username);
			List<UserItem> userItems = hibernateTemplate.find(
					"from UserItem useritem " + " where useritem.user=?", user);
			for (UserItem useritem : userItems) {
				hibernateTemplate.delete(useritem);
			}

			hibernateTemplate.delete(user);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
}